import { createApp } from 'vue'
import App from './App.vue'

// 自定义路由实现

// https://github.com/whinc/blog/issues/13
let sciterVue3Router = {
    install(app, options) {
        // 注册全局hash存储
        globalThis.__vue3_hash__ = ""
        // 注册router-view组件
        app.component("router-view", {
            data() {
                return {
                    routeView: ""
                }
            },
            template: `<template>
                    <component :is="routeView" />
                </template>`,
            created() {
                this.boundHashChange = this.onHashChange.bind(this)
            },
            beforeMount() {
                document.addEventListener('hashchange', this.boundHashChange)
            },
            mounted() {
                this.onHashChange()
            },
            beforeDestroy() {
                document.removeEventListener('hashchange', this.boundHashChange)
            },
            methods: {
                onHashChange() {
                    let path = globalThis.__vue3_hash__
                    this.routeView = this.$root.$routes[path] || null
                }
            }
        })
        // router-link
        app.component("router-link", {
            props: {
                to: String
            },
            template: `<template>
                    <a v-on:click="onClick" href=''><slot></slot></a>
                    </template>`,
            methods: {
                onClick() {
                    // 声明全局hash
                    globalThis.__vue3_hash__ = this.to;
                    document.dispatchEvent(new CustomEvent("hashchange"))
                }
            }
        })
    }
}
let app  = createApp(App)
// 使用路由实现
app.use(sciterVue3Router)
app.mount('#app')
